package modules.ins.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import luxing.common.service.impl.CommonServiceImpl;
import luxing.util.LoginUserUtil;
import modules.ins.entity.Insurance;
import modules.ins.service.InsuranceService;

/**
 * 
 * @author zzc
 *
 */
@Service("insuranceService")
@Transactional
public class InsuranceServiceImpl extends CommonServiceImpl implements InsuranceService {

	public void save(Insurance insurance) {
		String hql = "from Insurance where vehicle.id=? and type=? and tenantId=?";
		List<Insurance> list = listByHql(hql, insurance.getVehicle().getId(), insurance.getType(),
				LoginUserUtil.getLoginUser().getTenantId());
		// 历史记录提醒状态设置为null
		for (Insurance entity : list) {
			entity.setWarn(null);
			super.saveOrUpdate(entity);
		}
		super.save(insurance);
	}

	public void delete(Insurance insurance) {
		// 如果提醒状态不为空
		if (StringUtils.isNotBlank(insurance.getWarn())) {
			String hql = "from Insurance where vehicle.id=? and type=? and tenantId=? order by endDate desc";
			List<Insurance> list = listByHql(hql, insurance.getVehicle().getId(), insurance.getType(),
					LoginUserUtil.getLoginUser().getTenantId());
			if (CollectionUtils.isNotEmpty(list)) {
				Insurance entity = list.get(0);
				entity.setWarn(Insurance.WARN_NORMAL);
				saveOrUpdate(entity);
			}
		}
		super.delete(insurance);
	}

	public List<Insurance> listByVehicleAndType(String vehicleId, String type) {
		String hql = "from Insurance where vehicle.id=? and type=? and tenantId=? order by endDate desc";
		return listByHql(hql, vehicleId, type, LoginUserUtil.getLoginUser().getTenantId());
	}

	public List<Insurance> listByVehicle(String vehicleId) {
		String hql = "from Insurance where vehicle.id=?";
		return listByHql(hql, vehicleId);
	}

	public void updateWarn(String vehicleId, String warn) {
		String hql = "update Insurance set warn=? where vehicle.id=? and warn!=? and warn!=null and tenantId=?";
		executeHql(hql, warn, vehicleId, warn, LoginUserUtil.getLoginUser().getTenantId());
	}
}
